<template>

  <div class="app-container" style="background-color: #f0f2f5;">
    <el-row :gutter="10">
      <el-card style="padding: 0 10px; margin: 5px 5px 15px;">
        <p>今天是：{{ formattedDate }} 现在的时间是：{{ formattedTime }} 管理员【{{ name }}】欢迎回来！</p>
      </el-card>
    </el-row>
    <div v-if="checkPermission(permissionRoles.dashboard_data)">
      <el-row :gutter="10">
        <el-col :md="6">
          <el-card>
            <el-table :data="serverList" height="205">
              <el-table-column prop="show_name" label="最新开服" align="center"></el-table-column>
              <el-table-column prop="open_time" label="开服时间" align="center"></el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :md="6">
          <el-card>
            <el-table :data="rechargeRankList" height="205">
              <el-table-column prop="actor_name" label="角色名" align="center"></el-table-column>
              <el-table-column prop="sid" label="服务器" align="center"></el-table-column>
              <el-table-column prop="amount" label="今日充值金额" align="center"></el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :md="6">
          <el-card>
            <el-table :data="monitorList" height="205">
              <el-table-column prop="info" label="监控记录"></el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :md="6">
          <el-card>
            <el-table :data="loginList" height="205">
              <el-table-column prop="operate_dt" width="140px" label="登录记录"></el-table-column>
              <el-table-column prop="account"></el-table-column>
              <el-table-column prop="name"></el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="10" style="margin-top: 15px;">
        <el-col :md="6">
          <el-card>
            <div style="width: 130px;margin: 15px auto 0;">总注册：{{ treg }}</div>
            <div ref="registerPie" style="width: 100%; height: 350px;"></div>
          </el-card>
        </el-col>
        <el-col :md="6">
          <el-card>
            <div style="width: 130px;margin: 15px auto 0;">总充值：{{ trec }}</div>
            <div ref="rechargePie" style="width: 100%; height: 350px;"></div>
          </el-card>
        </el-col>
        <el-col :md="6">
          <el-card>
            <div style="width: 130px;margin: 15px auto 0;">昨日注册：{{ tyreg }}</div>
            <div ref="yregisterPie" style="width: 100%; height: 350px;"></div>
          </el-card>
        </el-col>
        <el-col :md="6">
          <el-card>
            <div style="width: 130px;margin: 15px auto 0;">昨日充值：{{ tyrec }}</div>
            <div ref="yrechargePie" style="width: 100%; height: 350px;"></div>
          </el-card>
        </el-col>
      </el-row>
      <el-row>
        <el-col :md="24">
          <el-card style="margin-top: 15px;">
            <el-table :data="overData" style="width: 100%">
              <el-table-column label="概览数据" align="center">
                <template slot-scope="{row}">
                  {{ row.field | fieldFilter }}
                </template>
              </el-table-column>
              <el-table-column prop="bnum" :label="`前日 (${preday})`" align="center"></el-table-column>
              <el-table-column prop="ynum" :label="`昨日 (${yesterday})`" align="center"></el-table-column>
              <el-table-column label="昨日增长率" align="center">
                <template slot-scope="{row}">
                  <span v-if="row.ynum_rate<0" style="color:red">{{ row.ynum_rate }}%</span>
                  <span v-else-if="row.ynum_rate===0" style="#333">{{ row.ynum_rate }}</span>
                  <span v-else-if="row.ynum_rate>0" style="color: #37B328">{{ row.ynum_rate }}%</span>
                </template>
              </el-table-column>
              <el-table-column prop="tnum" :label="`今日 (${today})`" align="center"></el-table-column>
              <el-table-column label="今日增长率" align="center">
                <template slot-scope="{row}">
                  <span v-if="row.tnum_rate<0" style="color:red">{{ row.tnum_rate }}%</span>
                  <span v-else-if="row.tnum_rate===0" style="#333">{{ row.tnum_rate }}</span>
                  <span v-else-if="row.tnum_rate>0" style="color: #37B328">{{ row.tnum_rate }}%</span>
                </template>
              </el-table-column>
              <el-table-column prop="max_num" label="历史最高" align="center"></el-table-column>
              <el-table-column prop="max_date" label="历史日期" align="center"></el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import checkPermission from '@/utils/permission' // 权限判断函数
import { getLastServerList, getOverviewList, getLogLoginList, getTodayRechargeRank, getPieData, getMonitorLog } from '@/api/user'
export default {
  filters: {
    fieldFilter(field) {
      const fieldMap = {
        'register': '注册',
        'dau': '活跃',
        'actor': '创角',
        'actor_old': '滚服人数',
        'recharge_num': '充值人数',
        'recharge_amount': '充值',
        'recharge_rate': '付费率',
        'arpu': 'ARPU',
        'register_recharge_num': '注册充值人数',
        'register_recharge_amount': '注册充值',
        'register_recharge_rate': '注册付费率',
        'register_recharge_arpu': '注册付费ARPU',
        'max_online': '最高在线人数',
        'avg_online': '平均在线人数',
        'top_recharge_player': '最高充值玩家',
        'top_recharge_server': '最高充值服'
      }
      return fieldMap[field]
    }
  },
  data() {
    return {
      url: '',
      permissionRoles: this.$store.state.user.permissionRoles,
      name: this.$store.state.user.name,
      roles: this.$store.state.user.roles,
      now: new Date(),
      serverList: [],
      loginList: [],
      rechargeRankList: [],
      monitorList: [],
      overData: [],
      pieData: [],
      regPieData: [],
      recPieData: [],
      yregPieData: [],
      yrecPieData: [],
      treg: 0,
      trec: 0,
      tyreg: 0,
      tyrec: 0,
      ydt: 'success',
      tdt: 'primary',
      pieType: 1,
      loading: false
    }
  },
  computed: {
    formattedDate() {
      const year = this.now.getFullYear()
      const month = String(this.now.getMonth() + 1).padStart(2, '0')
      const day = String(this.now.getDate()).padStart(2, '0')
      const weekDay = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][this.now.getDay()]
      return `${year}年${month}月${day}日，${weekDay}`
    },
    today() {
      return this.dateFilter(new Date())
    },
    yesterday() {
      return this.dateFilter(new Date().setDate(new Date().getDate() - 1))
    },
    preday() {
      return this.dateFilter(new Date().setDate(new Date().getDate() - 2))
    },
    formattedTime() {
      const hours = String(this.now.getHours()).padStart(2, '0')
      const minutes = String(this.now.getMinutes()).padStart(2, '0')
      const seconds = String(this.now.getSeconds()).padStart(2, '0')
      return `${hours}:${minutes}:${seconds}`
    },
    scWidth: function() {
      return document.getElementsByClassName('main-container')[0].clientWidth + 70 + 'px'
    },
    scHeight: function() {
      return '855px'
    }
  },
  mounted() {
    this.intervalId = setInterval(() => {
      this.now = new Date()
    }, 1000)
  },
  beforeUnmount() {
    clearInterval(this.intervalId)
  },
  created() {
    if (checkPermission(this.permissionRoles.dashboard_data)) {
      this.getServerList()
      this.getOverviewDataList()
      this.getLogLoginList()
      this.getRechargeRankList()
      this.getPieData()
      this.getMonitorLogList()
    }
  },
  methods: {
    checkPermission,
    async getServerList() {
      this.listLoading = true
      const res = await getLastServerList()
      this.listLoading = false
      this.serverList = res.data
      this.serverList.forEach((item, key) => {
        this.serverList[key].show_name = item.name + '(' + item.sid + ')'
      })
    },
    async getOverviewDataList() {
      this.listLoading = true
      const res = await getOverviewList()
      this.listLoading = false
      this.overData = res.data
    },
    async getLogLoginList() {
      this.listLoading = true
      const res = await getLogLoginList()
      this.listLoading = false
      this.loginList = res.data.items
    },
    async getRechargeRankList() {
      this.listLoading = true
      const res = await getTodayRechargeRank()
      this.listLoading = false
      this.rechargeRankList = res.data
    },
    async getMonitorLogList() {
      this.listLoading = true
      const res = await getMonitorLog()
      this.listLoading = false
      this.monitorList = res.data
    },
    async getPieData() {
      this.recPieData = []
      this.yrecPieData = []
      this.regPieData = []
      this.yregPieData = []
      this.treg = 0
      this.trec = 0
      this.tyreg = 0
      this.tyrec = 0
      this.listLoading = true
      const res = await getPieData({ type: this.pieType })
      this.listLoading = false
      this.pieData = res.data
      this.pieData.total.forEach(v => {
        this.regPieData.push({
          name: v.cpid,
          value: parseInt(v.register)
        })

        this.recPieData.push({
          name: v.cpid,
          value: parseInt(v.recharge_amount)
        })
      })

      this.pieData.total.forEach(v => {
        this.treg += parseInt(v.register)
        this.trec += parseInt(v.recharge_amount)
      })

      this.pieData.yesterday.forEach(v => {
        this.yregPieData.push({
          name: v.cpid,
          value: parseInt(v.register)
        })
        this.tyreg += parseInt(v.register)

        this.yrecPieData.push({
          name: v.cpid,
          value: parseInt(v.recharge_amount)
        })
        this.tyrec += parseInt(v.recharge_amount)
      })
      this.hanleChart()
    },
    handleYd() {
      this.pieType = 1
      this.ydt = 'success'
      this.tdt = 'primary'
      this.getPieData()
    },
    handleTd() {
      this.pieType = 2
      this.tdt = 'success'
      this.ydt = 'primary'
      this.getPieData()
    },
    hanleChart() {
      var regChart = echarts.init(this.$refs.registerPie)
      var recChart = echarts.init(this.$refs.rechargePie)
      var yregChart = echarts.init(this.$refs.yregisterPie)
      var yrecChart = echarts.init(this.$refs.yrechargePie)
      regChart.setOption(
        {
          tooltip: { trigger: 'item' },
          series: [
            {
              name: '总注册',
              type: 'pie',
              radius: '50%',
              label: { formatter: '{b}：{d}%', position: 'outside', overflow: 'break' },
              data: this.regPieData
            }
          ]
        }
      )
      recChart.setOption(
        {
          tooltip: { trigger: 'item' },
          series: [
            {
              name: '总充值',
              type: 'pie',
              radius: '50%',
              label: { formatter: '{b}：{d}%', position: 'outside', overflow: 'break' },
              data: this.recPieData
            }
          ]
        }
      )
      yregChart.setOption(
        {
          tooltip: { trigger: 'item' },
          series: [
            {
              name: '昨日注册',
              type: 'pie',
              radius: '50%',
              label: { formatter: '{b}：{d}%', position: 'outside', overflow: 'break' },
              data: this.yregPieData
            }
          ]
        }
      )
      yrecChart.setOption(
        {
          tooltip: { trigger: 'item' },
          series: [
            {
              name: '昨日充值',
              type: 'pie',
              radius: '50%',
              label: { formatter: '{b}：{d}%', position: 'outside', overflow: 'break' },
              data: this.yrecPieData
            }
          ]
        }
      )
    },
    dateFilter(d) {
      if (!d) return ''
      const date = new Date(d)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  }
}
</script>

<style lang="scss">
.el-card__body {
  padding: 0;
}

.offen_menu {
  margin-bottom: 15px;
}
</style>
